<template>
  <div ref="appRef" class="my-container-box">
    <div id="btnItem" class="title-box df aic jcsb">
      <div class="title">{{ state.title }}</div>
      <div v-if="state.isExport" class="btn" @click="handleExport()">
        <i class="iconfont icon-daochu"></i>导出
      </div>
    </div>
    <search-top-form
      class="search-form"
      :search-form="state.searchForm"
      :search-item="state.searchItem"
      @handle-search="handleSearch"
      @handle-reset="handleReset"
    ></search-top-form>
    <table-page-content
      :table-data="state.tableList"
      :table-headers="state.tableHeaders"
      :is-slot-num="false"
      :is-pager="false"
      :table-height="tableHeight"
      :is-more-header="true"
      :lazy-tree="true"
      :expand-all="false"
      :tree-props="{ children: 'children', hasChildren: 'haveChildren' }"
      @handle-lazy-load="getChildNode"
      @handle-expent-change="expentChange"
    >
    </table-page-content>
    <export-component
      ref="exportRef"
      :title="state.title"
      :area-code-list="state.areaCodeList"
      :user-type="state.userType"
      :table-title="state.title"
      :months="state.searchForm.months"
    ></export-component>
  </div>
</template>

<script setup lang="ts" name="TableList">
import { useTableHeight } from '@/hooks/tableHeight'
import useMenuStore from '@/store/modules/menu'
import useUserStore from '@/store/modules/user'
import exportComponent from '@/views/tableData/list/components/export.vue'
import { getTableDataDetail } from './api'
import { DicsObj, getDicsList } from '@/hooks/dicsData'
import { tableHeaders } from './config'
import { useProxy } from '@/utils/proxy'
const exportRef = ref()
const { proxy } = useProxy()
const menuStore = useMenuStore()
const userStore = useUserStore()
const menus = computed(() => menuStore.sidebarRouters)
const { appRef, tableHeight } = useTableHeight(true)
const state = reactive({
  title: '债务到期偿还情况表',
  searchForm: { months: '1', startDate: '', endDate: '', enterpriseType: '' },
  searchItem: [
    { name: '月份筛选', key: 'months', type: 'select', children: [] },
    {
      name: '起始时间',
      type: 'dateRange2',
      startProp: 'startDate',
      endProp: 'endDate',
      dateType: 'date',
      dateFormat: 'YYYY-MM-DD',
      disabled: true
    },
    { name: '企业类型', key: 'enterpriseType', type: 'select', children: [] }
  ] as any,
  userType: userStore.userInfo.userType as string,
  isExport: false,
  areaCodeList: [] as any[],
  tableHeaders: [] as any[],
  tableList: [] as any[]
})
watch(
  () => state.searchForm.months,
  (val: any) => {
    if (val == '0') {
      state.searchItem[1].disabled = false
      setNowDate(1)
    } else {
      setNowDate(val)
      state.searchItem[1].disabled = true
    }
  }
)
// 搜索
const handleSearch = () => {
  state.areaCodeList = []
  setTableHeader()
  getTableDetail()
}
const handleReset = () => {
  state.searchForm = { months: '1', startDate: '', endDate: '', enterpriseType: '' }
  handleSearch()
}
// 获取根节点数据
const getTableDetail = () => {
  state.tableList = []
  let params =
    state.searchForm.months == '0'
      ? {
          startDate: state.searchForm.startDate,
          endDate: state.searchForm.endDate,
          enterpriseType: state.searchForm.enterpriseType == '0' ? '' : state.searchForm.enterpriseType
        }
      : {
          months: state.searchForm.months,
          enterpriseType: state.searchForm.enterpriseType == '0' ? '' : state.searchForm.enterpriseType
        }
  getTableDataDetail({ allArea: false, areaCode: ' ', ...params }).then((res) => {
    state.tableList =
      res.data?.length > 0
        ? res.data.map((v: any) => {
            v.haveChildren = true
            v.level = 1
            return v
          })
        : []
  })
}
// 获取下级数据
const getChildNode = (row: any, node: any, resolve: any) => {
  let params = {} as any
  if (row.level == 1) {
    params = {
      allArea: state.userType == '0' ? false : true,
      areaCode: state.userType == '0' ? row.areaCode : ' '
    }
  } else {
    params = row?.corporationCode
      ? {
          allArea: false,
          areaCode: row.parentAreaCode,
          corporationCode: row.corporationCode
        }
      : {
          allArea: false,
          areaCode: row.areaCode || ' '
        }
  }
  let searchParams =
    state.searchForm.months == '0'
      ? {
          startDate: state.searchForm.startDate,
          endDate: state.searchForm.endDate,
          enterpriseType: state.searchForm.enterpriseType == '0' ? '' : state.searchForm.enterpriseType
        }
      : {
          months: state.searchForm.months,
          enterpriseType: state.searchForm.enterpriseType == '0' ? '' : state.searchForm.enterpriseType
        }
  getTableDataDetail({ ...params, ...searchParams }).then((res) => {
    let treeArr =
      res.data?.length > 0
        ? res.data.map((v: any, i: number) => {
            v.parentAreaCode = row.areaCode ?? ''
            v.level = row.level + 1
            return v
          })
        : []
    resolve(treeArr)
  })
}
// 动态设置表头
const setTableHeader = () => {
  let tableHeader = JSON.parse(JSON.stringify(tableHeaders))
  tableHeader[tableHeader.length - 1].cellName =
    state.searchForm.startDate + ' - ' + state.searchForm.endDate + '全口径债务余额'
  if (state.searchForm.months != '0') {
    let tableArr = []
    let nowYear = new Date().getFullYear()
    let nowMonth = new Date().getMonth() + 1
    for (let i = 0; i < Number(state.searchForm.months); i++) {
      let month = nowMonth + i > 12 ? nowMonth + i - 12 : nowMonth + i
      let year = nowMonth + i > 12 ? nowYear + 1 : nowYear
      let keyDate = year + '-' + (month < 10 ? `0${month}` : month)
      let concatHeader = {
        cellName: `${year}-${month}月到期债务`,
        isSumItem: false,
        cellAlignment: 'center',
        children: [
          {
            cellName: '小计',
            isSumItem: false,
            cellAlignment: 'center',
            cellDataKey: 'debtBalanceSum',
            children: [
              {
                cellName: '本金',
                isSumItem: false,
                cellAlignment: 'center',
                cellDataKey: 'debtMonPrincipalSum' + keyDate,
                cellWidth: 100
              },
              {
                cellName: '利息',
                isSumItem: false,
                cellAlignment: 'center',
                cellDataKey: 'debtMonInterestSum' + keyDate,
                cellWidth: 100
              }
            ]
          },
          {
            cellName: '一、政府显性债务到期金额',
            isSumItem: false,
            cellAlignment: 'center',
            children: [
              {
                cellName: '本金',
                isSumItem: false,
                cellAlignment: 'center',
                cellDataKey: 'governmentMonDebtPrincipal' + keyDate,
                cellWidth: 100
              },
              {
                cellName: '利息',
                isSumItem: false,
                cellAlignment: 'center',
                cellDataKey: 'governmentMonDebtInterest' + keyDate,
                cellWidth: 100
              }
            ]
          },
          {
            cellName: '二、政府隐性债务到期金额',
            isSumItem: false,
            cellAlignment: 'center',
            children: [
              {
                cellName: '本金',
                isSumItem: false,
                cellAlignment: 'center',
                cellDataKey: 'governmentMonImpDebtPrincipal' + keyDate,
                cellWidth: 100
              },
              {
                cellName: '利息',
                isSumItem: false,
                cellAlignment: 'center',
                cellDataKey: 'governmentMonImpDebtInterest' + keyDate,
                cellWidth: 100
              }
            ]
          },
          {
            cellName: '三、融资平台及国有企业债务到期金额（不含隐性债务）',
            isSumItem: false,
            cellAlignment: 'center',
            children: [
              {
                cellName: '本金',
                isSumItem: false,
                cellAlignment: 'center',
                cellDataKey: 'financingStateownedDebtPrincipal' + keyDate,
                cellWidth: 100
              },
              {
                cellName: '利息',
                isSumItem: false,
                cellAlignment: 'center',
                cellDataKey: 'financingStateownedDebtInterest' + keyDate,
                cellWidth: 100
              }
            ]
          }
        ]
      }
      tableArr.push(concatHeader)
    }
    state.tableHeaders = [...tableHeader, ...tableArr]
  } else {
    state.tableHeaders = tableHeader
  }
}
//获取权限
const getPower = () => {
  let menuItem = menus.value.filter((v: any) => v.path == '/tableData/index')[0] as any
  let index = menuItem.children.findIndex((v: any) => v.path == proxy.$route.fullPath)
  if (index != -1) {
    const rights = menuItem.children[index].meta.rights as any[]
    if (!rights?.length) {
      state.isExport = true
    } else {
      const hasPermission = rights.some((item: any) => {
        return item.meta.permissionKey.includes('export')
      })
      state.isExport = hasPermission ? true : false
    }
  }
}
// 展开行回调
const expentChange = (row: any, expend: boolean) => {
  let index = state.areaCodeList.findIndex((v) => v.id == row.id)
  if (index == -1) {
    state.areaCodeList.push({
      id: row.id,
      level: row.level,
      areaCode: row.areaCode,
      corporationCode: row?.corporationCode,
      parentAreaCode: row?.parentAreaCode,
      expend
    })
  } else {
    state.areaCodeList[index].expend = expend
  }
}
// 导出
const handleExport = () => {
  exportRef.value.state.show = true
}
// 设置当前日期时间段
const setNowDate = (mouths: number) => {
  let currentDate = new Date()
  let year = currentDate.getFullYear()
  let month = currentDate.getMonth() + 1 // 月份是从0开始的，所以要加1
  let date = '01'
  let currentEndDate = new Date(currentDate.setMonth(currentDate.getMonth() + Number(mouths)))
  let endYear = currentEndDate.getFullYear()
  let endMonth = currentEndDate.getMonth()
  let endDate = new Date(endYear, endMonth, 0).getDate()
  state.searchForm.startDate = year + '-' + (month < 10 ? `0${month}` : month) + '-' + date
  state.searchForm.endDate = endYear + '-' + (endMonth < 10 ? `0${endMonth}` : endMonth) + '-' + endDate
}
const init = () => {
  setNowDate(1)
  getDicsList(DicsObj.dataType, true).then((res: any) => {
    state.searchItem[0].children = res
  })
  getDicsList(DicsObj.enterpriseType).then((res: any) => {
    state.searchItem[2].children = res
    state.searchItem[2].children.unshift({ code: '0', name: '全部' })
  })
  getPower()
  setTableHeader()
  getTableDetail()
}
init()
</script>

<style lang="scss" scoped>
.title-box {
  padding-bottom: 10px;
  border-bottom: 1px solid #ccc;
  margin-bottom: 10px;
}
.title {
  font-size: 20px;
  color: #666666;
  box-sizing: border-box;
}
.btn {
  height: 30px;
  background: rgba(85, 141, 247, 0.1);
  border-radius: 4px 4px 4px 4px;
  opacity: 1;
  border: 1px solid $blue;
  padding: 0px 9px;
  text-align: center;
  line-height: 30px;
  color: $blue;
  font-size: 16px;
  cursor: pointer;
  .iconfont {
    margin-right: 4px;
    font-size: 13px;
    margin-bottom: 1px;
  }
}
</style>
